package com.zys.asseter.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zys.asseter.domain.dto.UserDTO;
import com.zys.asseter.domain.pojo.PageBean;
import com.zys.asseter.domain.pojo.UserEntity;
import com.zys.asseter.domain.vo.ManufacturerCountVo;
import com.zys.asseter.domain.vo.QueryVo;
import com.zys.asseter.domain.vo.TreeVo;
import com.zys.asseter.domain.vo.UserQueryVo;
import com.zys.asseter.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.apache.catalina.User;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserService {
    private final UserMapper userMapper;


   public List<TreeVo> getTypeTree() {
      List<UserEntity> users = userMapper.selectAll();

      Map<String, List<Integer>> collect = users.stream()
              .collect(Collectors.groupingBy(UserEntity::getName,
                      Collectors.mapping(UserEntity::getAge, Collectors.toList())
              ));

      Map<Integer,String> map = new HashMap<>();
      List<QueryVo> user =userMapper.getCharacterAll();
       for (QueryVo queryVo : user) {
          map.put(queryVo.getAge(),queryVo.getCharacter());
       }
      List<TreeVo> collect1 = collect.entrySet().stream()
              .map(entry -> {
                 TreeVo treeVo = new TreeVo();
                 treeVo.setName(entry.getKey());
                 treeVo.setChildren(entry.getValue().stream().map(
                         age -> {
                            TreeVo treeVo1 = new TreeVo();
                            treeVo1.setAge(age);
//                            treeVo1.setName(entry.getKey());
                            treeVo1.setCharacter(map.get(age));
                            return treeVo1;
                         }).collect(Collectors.toList()));
                 return treeVo;
              }).collect(Collectors.toList());
      return collect1;
   }


    public PageBean<UserEntity> selectCondition(UserQueryVo userQueryVo) {
        PageBean<UserEntity> pageBean = new PageBean<>();
        PageHelper.startPage(userQueryVo.getPageNum(), userQueryVo.getPageSize());
        List<UserEntity> userEntities = userMapper.selectCondition(userQueryVo.getName(), userQueryVo.getAge());
        Page<UserEntity> p = (Page<UserEntity>) userEntities;
        pageBean.setTotal(p.getTotal());
        pageBean.setItems(p.getResult());
        return pageBean;
    }

    public void insert(UserDTO userDTO) {
       UserEntity userEntity = new UserEntity();
       BeanUtils.copyProperties(userDTO,userEntity);
        userMapper.insert(userEntity);
    }

    public void update(String name,String count) {
        if(!count.equals("0")){
            userMapper.update(name, count);
        }
    }
}
